<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/GPL-3.0
 * @link https://www.gougucms.com
 */

declare (strict_types=1);

namespace app\finance\controller;

use app\base\BaseController;
use app\finance\model\XzSalary;
use app\finance\model\XzSalaryDetail;
use think\facade\Db;
use think\facade\View;
use app\user\model\Admin as AdminList;
use app\user\validate\AdminCheck;

class Salary extends BaseController
{

    public function index()
    {
        if (request()->isAjax()) {
            if (request()->isAjax()) {
                $param = get_params();
                $where = array();
                $whereOr = array();
                if (!empty($param['keywords'])) {
                    $where[] = ['a.title', 'like', '%' . $param['keywords'] . '%'];
                }

                $where[] = ['a.delete_time', '=', 0];
                $model = new XzSalary();
                $list = $model->get_list($param, $where, $whereOr);
                return table_assign(0, '', $list);
            } else {

                return view();
            }
        } else {
            return view();
        }
    }


    public function base_user()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $where = array();
            if (!empty($param['keywords'])) {
                $where[] = ['id|username|name|nickname|mobile|desc', 'like', '%' . $param['keywords'] . '%'];
            }
            $where[] = ['status', '<', 2];
            if (isset($param['status']) && $param['status'] != '') {
                $where[] = ['status', '=', $param['status']];
            }
            if (!empty($param['type'])) {
                $where[] = ['type', '=', $param['type']];
            }
            if (!empty($param['did'])) {
                $department_array = get_department_son($param['did']);
                $where[] = ['did', 'in', $department_array];
            }
            $where[] = ['id', '<>', 1];
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $admin = AdminList::where($where)
                ->order('id desc')
                ->paginate($rows, false, ['query' => $param])
                ->each(function ($item, $key) {
                    $item->department = Db::name('Department')->where(['id' => $item->did])->value('title');
                    $item->position = Db::name('Position')->where(['id' => $item->position_id])->value('title');
                    $item->entry_time = empty($item->entry_time) ? '-' : date('Y-m-d', $item->entry_time);
                });
            return table_assign(0, '', $admin);
        } else {
            return view();
        }
    }


    //添加&&编辑
    public function add()
    {
        $param = get_params();
        unset($param['file']);
        if (empty($param['handle_time'])) {
            unset($param['handle_time']);
        }

        if (request()->isAjax()) {
            if (!empty($param['id']) && $param['id'] > 0) {
                $param['update_time'] = time();
                $model = new AdminList();
                $res = $model->field(true)->update($param);
                if ($res) {
                    return to_assign();
                } else {
                    return to_assign(1, '操作失败');
                }
            }
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            View::assign('id', $id);

            if ($id > 0) {
                $detail = AdminList::where('id', $id)->find();
                $detail['department'] = Db::name('Department')->where(['id' => $detail['did']])->value('title');
                View::assign('detail', $detail);
            }
            return view();
        }
    }

    //删除
    public function delete()
    {
        if (request()->isDelete()) {
            $id = get_params("id");
            $data['id'] = $id;
            $data['delete_time'] = time();
            if (Db::name('xz_salary')->update($data) !== false) {
                add_log('delete', $id);
                return to_assign(0, "删除成功");
            } else {
                return to_assign(1, "删除失败");
            }
        } else {
            return to_assign(1, "错误的请求");
        }
    }

    //添加&&编辑
    public function detail()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $id = isset($param['id']) ? $param['id'] : 0;
            if ($id == 0) {
                return to_assign(1, "缺少参数");
            }
            $where = array();
            $where[] = ['a.delete_time', '=', 0];
            $where[] = ['a.salary_id', '=', $id];
            $whereOr = [];

            $model = new XzSalaryDetail();
            $list = $model->get_list($param, $where, $whereOr);
            $data['data'] = $list;
            return table_assign(0, '', $data);
        } else {
            $param = get_params();
            $id = isset($param['id']) ? $param['id'] : 0;
            $model = new XzSalary();
            $detail = $model->detail($id);
            View::assign('detail', $detail);
            View::assign('id', $id);

            $flows = Db::name('FlowStep')->where(['action_id' => $detail['id'], 'type' => 26, 'sort' => $detail['check_step_sort'], 'delete_time' => 0])->find();
            $detail['check_user'] = '-';
            $detail['copy_user'] = '-';
            $check_user_ids = [];
            if ($detail['check_status'] == 1) {
                if ($flows['flow_type'] == 1) {
                    $detail['check_user'] = '部门负责人';
                    $check_user_ids[] = get_department_leader($detail['admin_id']);
                } else if ($flows['flow_type'] == 2) {
                    $detail['check_user'] = '上级部门负责人';
                    $check_user_ids[] = get_department_leader($detail['admin_id'], 1);
                } else {
                    $check_user_ids = explode(',', $flows['flow_uids']);
                    $check_user = Db::name('Admin')->where('id', 'in', $flows['flow_uids'])->column('name');
                    $detail['check_user'] = implode(',', $check_user);
                }
            }

            if ($detail['copy_uids'] != '') {
                $copy_user = Db::name('Admin')->where('id', 'in', $detail['copy_uids'])->column('name');
                $detail['copy_user'] = implode(',', $copy_user);
            }
            $is_check_admin = 0;
            $is_create_admin = 0;
            if ($detail['admin_id'] == $this->uid) {
                $is_create_admin = 1;
            }
            if (in_array($this->uid, $check_user_ids)) {
                $is_check_admin = 1;
                //当前审核节点详情
                if ($flows['flow_type'] == 4) {
                    $check_count = Db::name('FlowRecord')->where(['action_id' => $detail['id'], 'type' => 26, 'step_id' => $flows['id'], 'check_user_id' => $this->uid])->count();
                    if ($check_count > 0) {
                        $is_check_admin = 0;
                    }
                }
            }

            $check_record = Db::name('FlowRecord')->field('f.*,a.name,a.thumb')
                ->alias('f')
                ->join('Admin a', 'a.id = f.check_user_id', 'left')
                ->where(['f.action_id' => $detail['id'], 'f.type' => 26])
                ->order('check_time desc')
                ->select()->toArray();
            foreach ($check_record as $kk => &$vv) {
                $vv['check_time_str'] = date('Y-m-d H:i', $vv['check_time']);
                $vv['status_str'] = '提交';
                if ($vv['status'] == 1) {
                    $vv['status_str'] = '审核通过';
                } else if ($vv['status'] == 2) {
                    $vv['status_str'] = '审核拒绝';
                }
                if ($vv['status'] == 3) {
                    $vv['status_str'] = '撤销';
                }
            }

            View::assign('is_create_admin', $is_create_admin);
            View::assign('is_check_admin', $is_check_admin);
            View::assign('check_record', $check_record);
            View::assign('flows', $flows);
            View::assign('uid', $this->uid);



            return view();
        }
    }

    public function report()
    {
        $param = get_params();

        if (request()->isAjax()) {
            $param['check_status'] = 1;
            $param['check_step_sort'] = 0;
            $flow_list = Db::name('Flow')->where('id', $param['flow_id'])->value('flow_list');
            $flow = unserialize($flow_list);
            //删除原来的审核流程和审核记录
            Db::name('FlowStep')->where(['action_id' => $param['id'], 'type' => 26, 'delete_time' => 0])->update(['delete_time' => time()]);
            Db::name('FlowRecord')->where(['action_id' => $param['id'], 'type' => 26, 'delete_time' => 0])->update(['delete_time' => time()]);
            if (!isset($param['check_admin_ids'])) {
                if ($flow[0]['flow_type'] == 1) {
                    //部门负责人
                    $leader = get_department_leader($this->uid);
                    if ($leader == 0) {
                        return to_assign(1, '审批流程设置有问题：当前部门负责人还未设置，请联系HR或者管理员');
                    } else {
                        $param['check_admin_ids'] = $leader;
                    }
                } else if ($flow[0]['flow_type'] == 2) {
                    //上级部门负责人
                    $leader = get_department_leader($this->uid, 1);
                    if ($leader == 0) {
                        return to_assign(1, '审批流程设置有问题：上级部门负责人还未设置，请联系HR或者管理员');
                    } else {
                        $param['check_admin_ids'] = $leader;
                    }
                } else {
                    $param['check_admin_ids'] = $flow[0]['flow_uids'];
                }
                foreach ($flow as $key => &$value) {
                    $value['action_id'] = $param['id'];
                    $value['sort'] = $key;
                    $value['type'] = 26;
                    $value['create_time'] = time();
                }
                //增加审核流程
                Db::name('FlowStep')->strict(false)->field(true)->insertAll($flow);
            } else {
                $flow_step = array(
                    'action_id' => $param['id'],
                    'type' => 26,
                    'flow_uids' => $param['check_admin_ids'],
                    'create_time' => time()
                );
                //增加审核流程
                Db::name('FlowStep')->strict(false)->field(true)->insertGetId($flow_step);
            }
            $res = XzSalary::where('id', $param['id'])->strict(false)->field(true)->update($param);
            if ($res !== false) {
                $appro['action_id'] = $param['id'];
                $appro['type'] = 43;
                $appro['start_time'] = time();
                $appro['admin_id'] = $this->uid;
                $appro['department_id'] = $this->did;
                $appro['create_time'] = time();
                $appro['flow_id'] = $param['flow_id'];
                $appro['check_admin_ids'] = $param['check_admin_ids'];
                $appro['copy_uids'] = $param['copy_uids'];
                $appro['check_status'] = $param['check_status'];
                if (empty(Db::name('Approve')->where('action_id', $appro['action_id'])->where('type', $appro['type'])->find())) {
                    Db::name('Approve')->strict(false)->field(true)->insertGetId($appro);
                } else {
                    Db::name('Approve')->where('action_id', $appro['action_id'])->where('type', $appro['type'])->strict(false)->field(true)->update($appro);
                }
                //添加提交申请记录
                $checkData = array(
                    'action_id' => $param['id'],
                    'check_user_id' => $this->uid,
                    'content' => '重新提交申请',
                    'type' => 26,
                    'check_time' => time(),
                    'create_time' => time()
                );
                $record_id = Db::name('FlowRecord')->strict(false)->field(true)->insertGetId($checkData);
                add_log('edit', $param['id'], $param);
                //发送消息通知
                $msg = [
                    'from_uid' => $this->uid,
                    'title' => '财务-薪资',
                    'action_id' => $param['id']
                ];
                $users = $param['check_admin_ids'];
                sendMessage($users, 271, $msg);
                return to_assign();
            } else {
                return to_assign(1, '操作失败');
            }
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            View::assign('id', $id);
            $department = $this->did;
            //获取发票审批流程
            $flows = get_type_department_flows(26, $department);
            View::assign('user', get_admin($this->uid));
            View::assign('flows', $flows);
            if ($id > 0) {
                $model = new XzSalary();
                $detail = $model->detail($id);
                View::assign('detail', $detail);
            }
            return view();
        }
    }


    //薪资生成
    public function produce()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $detail_all = [];
            $names = $param['names'];
            $departments = $param['departments'];
            $base_salarys = $param['base_salarys'];
            $insurance_deducts = $param['insurance_deducts'];
            $allowances = $param['allowances'];
            $performances = $param['performances'];
            $moneys = $param['moneys'];
            $remarks = $param['remarks'];
            $ids = $param['ids'];
            $checkings = $param['checkings'];
            $data = [
                'title' => $param['title'] ?? '',
                'month' => ($param['year'] ?? '').($param['month'] ?? ''),
                'admin_id'=>$this->uid,
                'number' => count($ids),
                'create_time'=>time()
            ];
            $pid =  Db::name('xz_salary')->insertGetId($data);
            if(!$pid){
                return to_assign(1, '生成失败');
            }
            foreach ($names as $k => $v){
                $detail_all[$k]['name'] = $v;
            }
            foreach ($departments as $k => $v){
                $detail_all[$k]['department'] =$v;
            }
            foreach ($base_salarys as $k => $v){
                $detail_all[$k]['base_salary'] = $v;
            }
            foreach ($insurance_deducts as $k => $v){
                $detail_all[$k]['security'] = $v;
            }
            foreach ($allowances as $k => $v){
                $detail_all[$k]['allowance'] = $v;
            }
            foreach ($performances as $k => $v){
                $detail_all[$k]['performance'] = $v;
            }
            foreach ($checkings as $k => $v){
                $detail_all[$k]['checking'] = $v;
            }
            foreach ($moneys as $k => $v){
                $detail_all[$k]['money'] = $v;
            }
            foreach ($remarks as $k => $v){
                $detail_all[$k]['remark'] = $v;
            }
            foreach ($ids as $k => $v){
                $detail_all[$k]['admin_id'] = $v;
                $detail_all[$k]['salary_id'] = $pid;
            }
            if($pid){
               $res =  Db::name('xz_salary_detail')->insertAll($detail_all);
               if($res){
                   return to_assign(0,'生成成功！');
               }
            }
        }else{
            $param = get_params();
            $where[] = ['status', '<', 2];
            $where[] = ['id', '<>', 1];
            $admin = AdminList::where($where)
                ->field('id,did,name,base_salary,insurance_deduct')
                ->order('id desc')
                ->select()->toArray();
            $title = $param['title'] ?? '';
            View::assign('title', $title);
            $year = $param['year'] ?? '';
            View::assign('year', $year);
            $month = $param['month'] ?? '';
            View::assign('month', $month);


            $date =$year.'-'.$month.'-01';

            foreach ($admin as $k => $v) {
                $admin[$k]['department'] = Db::name('Department')->where(['id' => $v['did']])->value('title');
                $performance = $this->performance($v['id'],$date);
                $admin[$k]['money'] = $performance+$v['base_salary']-$v['insurance_deduct'];
                $admin[$k]['performance'] =$performance;
            }
            View::assign('admin', $admin);
            return view();
        }
    }

    public function fafang(){
        if (request()->isDelete()) {
            $id = get_params("id");
            $data['id'] = $id;
            $data['ff_at'] = date('Y-m-d');
            $data['status'] = 1;
            if (Db::name('xz_salary')->update($data) !== false) {
                Db::name('xz_salary_detail')->where('salary_id',$id)->update(['state'=>1]);
                return to_assign(0, "发放成功");
            } else {
                return to_assign(1, "发放失败");
            }
        } else {
            return to_assign(1, "错误的请求");
        }
    }

    private function performance($id, $date = '2023-12-15')
    {

        $start = date('Y-m-01 00:00:00', strtotime($date));
        $start = strtotime($start);
        $timestamp = strtotime($date);
        // 计算下个月第一天的时间戳
        $nextMonthFirstDayTimestamp = strtotime('first day of next month', $timestamp);
        // 转换成日期字符串并输出结果
        $end = date('Y-m-d 00:00:00', $nextMonthFirstDayTimestamp);
        $end = strtotime($end);
        $money1 = $this->xinban($id, $start, $end);
        $money2 = $this->binggou($id, $start, $end);
        $money3 = $this->baoshui($id, $start, $end);
        $money4 = $this->wxkh($id, $start, $end);
        $money5 = $this->caiwubaoshui($id, $start, $end);

        $money6 = $this->caiwuwxkh($id, $start, $end);
        $money7 = $this->liepin_qy($id, $start, $end);
        $money8 = $this->liepin_rc($id, $start, $end);
        $money9 = $this->caibiangeng($id, $start, $end);
        $money10 = $this->xiangmu($id, $start, $end);
        return $money1 + $money2 + $money3 + $money4 + $money5 + $money6 + $money7+ $money8+ $money9+ $money10;
    }

    private function xinban($id, $start, $end)
    {
        $db = db::name('license_cert')
            ->where('a.delete_time', 0)
            ->where('a.sign_id', $id)
            ->field('a.*')
            ->alias('a');
        $db->join('license_payment b', 'a.id = b.cert_id');
        $db->where('b.delete_time', 0);
        $db->where('b.account_status', 1);
        $db->where('b.check_time', '>=', $start);
        $db->where('b.check_time', '<=', $end);
        $deduct = $db->sum('a.deduct');
        return $deduct;
    }

    private function binggou($id, $start, $end)
    {
        $db = db::name('transfer')
            ->where('a.delete_time', 0)
            ->where('a.sign_id', $id)
            ->field('a.*')
            ->alias('a');
        $db->join('transfer_playback b', 'a.id = b.transfer_id');
        $db->where('b.delete_time', 0);
        $db->where('b.remit_account_status', 1);
        $db->where('b.check_time', '>=', $start);
        $db->where('b.check_time', '<=', $end);
        $deduct = $db->sum('a.deduct');
        return $deduct;
    }

    private function baoshui($id, $start, $end)
    {
        $db = db::name('declare_tax')
            ->where('a.delete_time', 0)
            ->where('a.sign_id', $id)
            ->field('a.*')
            ->alias('a');
        $db->join('declare_tax_payment b', 'a.id = b.tax_id');
        $db->where('b.delete_time', 0);
        $db->where('b.account_status', 1);
        $db->where('b.check_time', '>=', $start);
        $db->where('b.check_time', '<=', $end);
        $deduct = $db->sum('a.deduct');
        return $deduct;
    }

    private function wxkh($id, $start, $end)
    {
        $db = db::name('security_account')
            ->where('a.delete_time', 0)
            ->where('a.sign_id', $id)
            ->field('a.*')
            ->alias('a');
        $db->join('security_account_payment b', 'a.id = b.account_id');
        $db->where('b.delete_time', 0);
        $db->where('b.account_status', 1);
        $db->where('b.check_time', '>=', $start);
        $db->where('b.check_time', '<=', $end);
        $deduct = $db->sum('a.deduct');
        return $deduct;
    }

    private function caiwubaoshui($id, $start, $end)
    {
        $deduct = db::name('declare_tax_finance')
            ->where('delete_time', 0)
            ->where('tax_id', $id)
            ->where('check_time', '>=', $start)
            ->where('check_time', '<=', $end)
            ->sum('deduct');
        return $deduct;
    }
    private function caibiangeng($id, $start, $end)
    {
        $deduct = db::name('transact')
            ->where('delete_time', 0)
            ->where('handle_person_id', $id)
            ->where('check_time', '>=', $start)
            ->where('check_time', '<=', $end)
            ->sum('deduct');
        return $deduct;
    }
    private function caiwuwxkh($id, $start, $end)
    {
        $deduct = db::name('security_account_finance')
            ->where('delete_time', 0)
            ->where('open_id', $id)
            ->where('check_time', '>=', $start)
            ->where('check_time', '<=', $end)
            ->sum('deduct');
        return $deduct;
    }
    private function xiangmu($id, $start, $end)
    {
        $deduct =db::name('license_project')
            ->where('delete_time', 0)
            ->where('report_id', $id)
            ->where('check_time', '>=', $start)
            ->where('check_time', '<=', $end)
            ->sum('deduct');
        return $deduct;
    }

    private function liepin_qy($id, $start, $end)
    {
        $db = db::name('bitjob_enterprise')
            ->where('a.delete_time', 0)
            ->where('a.battle_user_id', $id)
            ->field('a.battle_money,a.bitjob_ids,a.certs')
            ->alias('a');
        $db->join('bitjob_payment b', 'a.id = b.bitjob_id');
        $db->where('b.delete_time', 0);
        $db->where('b.account_status', 1);
        $db->where('b.check_time', '>=', $start);
        $db->where('b.check_time', '<=', $end);
        $list = $db->select()->toArray();
        $money = 0;
        foreach ($list as $k => $v) {
            if($v['certs']){
                $certs = json_decode($v['certs'],true);
                foreach ($certs as $k1=>$v1){
                    $money += $v1['new_money'] - $v1['money'];
                }

            }
        }
        return $this->liepin_conf($money,1);
    }

    private function liepin_rc($id, $start, $end)
    {
        $db = db::name('bitjob_enterprise')
            ->where('a.delete_time', 0)
            ->where('a.febpei_uid', $id)
            ->field('a.battle_money,a.bitjob_ids,a.certs')
            ->alias('a');
        $db->join('bitjob_payment b', 'a.id = b.bitjob_id');
        $db->where('b.delete_time', 0);
        $db->where('b.account_status', 1);
        $db->where('b.check_time', '>=', $start);
        $db->where('b.check_time', '<=', $end);
        $list = $db->group('a.id')->select()->toArray();
        $money = 0;
        foreach ($list as $k => $v) {
            if($v['certs']){
                $certs = json_decode($v['certs'],true);
                foreach ($certs as $k1=>$v1){
                    $money += $v1['new_money'] - $v1['money'];
                }
            }
        }
        return $this->liepin_conf($money,2);
    }

    private function liepin_conf($money, $type = 1)
    {
        $tc_money = 0;
        if ($type == 1) {//企业
            if ($money < 15000) {
                $tc_money = $money * 0.1;
            } elseif ($money >= 15000 && $money < 22500) {
                $tc_money = $money * 0.12;
            } elseif ($money >= 22500 && $money < 30000) {
                $tc_money = $money * 0.14;
            } elseif ($money >= 30000) {
                $tc_money = $money * 0.16;
            }
        } else {//人才
            if ($money < 15000) {
                $tc_money = $money * 0.11;
            } elseif ($money >= 15000 && $money < 22500) {
                $tc_money = $money * 0.13;
            } elseif ($money >= 22500 && $money < 30000) {
                $tc_money = $money * 0.15;
            } elseif ($money >= 30000) {
                $tc_money = $money * 0.17;
            }
        }

        return $tc_money;
    }
}
